package com.example.download;

import android.Manifest;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;

import android.util.Log;
import android.view.SurfaceView;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static DownloadManager downloadManager;
    private static SurfaceView surfaceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (getSupportActionBar() != null){
            getSupportActionBar().hide();
        }
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);


        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
        }

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
        }

        surfaceView = (SurfaceView) findViewById(R.id.surface_view);

        downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        String address = "http://vfx.mtime.cn/Video/2019/03/19/mp4/190319104618910544.mp4";
        Uri uri = Uri.parse(address);
        DownloadManager.Request downRequest = new DownloadManager.Request(uri);
        downRequest.setTitle("标题");
        downRequest.setDescription("描述");
        downRequest.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        downRequest.setVisibleInDownloadsUi(true);
        downRequest.setDestinationInExternalFilesDir(MainActivity.this, Environment.DIRECTORY_DOWNLOADS, "1.mp4");
        downloadManager.enqueue(downRequest);

    }

    public static class DownloadCompleteReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                Log.i("TAG", "downId=" + downId);
                getPath(context,downId);
            }
        }
    }

    public static class NotificationClickReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
                long[] downsIds = intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);
                for (long downId : downsIds) {
                    Log.i("TAG", "downsId=" + downId);
                }
            }
        }
    }

    public static void getPath(Context context, long downloadID) {
        Cursor c = downloadManager.query(new DownloadManager.Query().setFilterById(downloadID));
        if (c == null) {
            Toast.makeText(context, "Download not found!", Toast.LENGTH_LONG).show();
        } else {
            c.moveToFirst();
            Log.d("TAG", "COLUMN_ID: " + c.getLong(c.getColumnIndex(DownloadManager.COLUMN_ID)));
            Log.d("TAG", "COLUMN_BYTES_DOWNLOADED_SO_FAR: " + c.getLong(c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)));
            Log.d("TAG", "COLUMN_LAST_MODIFIED_TIMESTAMP: " + c.getLong(c.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP)));
            Log.d("TAG", "COLUMN_LOCAL_URI: " + c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)));
            Log.d("TAG", "COLUMN_STATUS: " + c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)));
            Log.d("TAG", "COLUMN_REASON: " + c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON)));
            Toast.makeText(context, statusMessage(c), Toast.LENGTH_LONG).show();

            try {
                MediaPlayer mediaPlayer = new MediaPlayer();
                Uri uri = Uri.parse(c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)));
                Log.d("TAG",uri.getPath());
                mediaPlayer.setDataSource(c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)));
                mediaPlayer.setSurface(surfaceView.getHolder().getSurface());
                mediaPlayer.prepare();
                mediaPlayer.start();
            } catch (IOException e) {
                Log.d("TAG",e.getMessage());
                e.printStackTrace();
            }
        }
    }

    private static String statusMessage(Cursor c) {
        switch (c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS))) {
            case DownloadManager.STATUS_SUCCESSFUL:
                return "Download complete!";
            default:
                return "";
        }
    }


}
